<template>
    <div class="login-log-container">
        <!-- 表单搜索项 -->
        <el-form :model="params">
            <el-row :gutter="20">
                <el-col :span="5">
                    <el-form-item label="维修单编号">
                        <el-input v-model="params.repairNo" placeholder="请输入维修单编号" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="维修单名称">
                        <el-input v-model="params.repairName" placeholder="请输入维修单名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="设备编码">
                        <el-input v-model="params.deviceNo" placeholder="请输入设备编码" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="设备名称">
                        <el-input v-model="params.deviceName" placeholder="请输入设备名称" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="5">
                    <el-form-item label="维修结果">
                        <el-select v-model="params.repairResults" placeholder="请输入维修结果" @change="handleStatusChange">
                            <el-option label="维修成功" value="0" />
                            <el-option label="报废" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="单据状态">
                        <el-select v-model="params.documentStatus" placeholder="请输入状态" @change="handleStatusChange">
                            <el-option label="草稿" value="0" />
                            <el-option label="已确认" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" plain :icon="Refresh" @click="handleReset">重置</el-button>
            </el-row>
        </el-form>

        <!-- 按钮组 -->
        <el-row class="button-group">
            <el-col :span="10">
                <div>
                    <el-button type="primary" :icon="Plus" plain @click="openInsert">新增</el-button>
                    <el-button type="danger" plain :disabled="deleteDisabled" :icon="Delete"
                        @click="handleDelete">删除</el-button>
                    <el-button type="danger" plain :icon="Delete" @click="clearAll">清空</el-button>
                </div>
            </el-col>
            <el-col :span="14">
                <div class="button-right">
                    <el-tooltip content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle />
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">
                        <el-button :icon="Refresh" circle />
                    </el-tooltip>
                </div>
            </el-col>
        </el-row>

        <!-- 数据表格 -->
        <el-row>
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="40" />
                <el-table-column prop="repairNo" label="维修单编号" align="center" />
                <el-table-column prop="repairName" label="维修单名称" align="center" />
                <el-table-column prop="equipment.deviceNo" label="设备编码" align="center" />
                <el-table-column prop="equipment.deviceName" label="设备名称" align="center" />
                <el-table-column prop="repairTime" label="保修日期" align="center" />
                <el-table-column prop="completionDate" label="维修完成日期" align="center" />
                <el-table-column prop="acceptanceDate" label="验收日期" align="center" />
                <el-table-column prop="repairResults" label="维修结果" align="center">
                    <template #default="scope">
                        {{
                            scope.row.planType === '0' ? '维修成功' :
                                scope.row.planType === '1' ? '报废' : '未知'
                        }}
                    </template>
                </el-table-column>
                <el-table-column prop="repairPersonnel" label="维修人员" align="center" />
                <el-table-column prop="acceptancePersonnel" label="验收人员" align="center" />
                <el-table-column prop="documentStatus" label="状态" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.documentStatus === '0' ? 'success' : 'danger'">
                            {{ scope.row.documentStatus === '0' ? '草稿' : '已确认' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200px">
                    <template #default="scope">
                        <el-button :row="scope.row" type="primary" @click="openUpdate(scope.row)" text size="small"
                            :icon="EditPen">修改</el-button>
                        <el-button type="danger" text size="small" :icon="Delete" :row="scope.row"
                            @click="deleteItem(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>

        <!-- 分页组件 -->
        <el-row>
            <el-col :span="24">
                <div class="demo-pagination-block">
                    <el-pagination :current-page="params.currentPage" :page-size="params.pageSize" background
                        :default-page-size="params.pageSize" :page-sizes="pageSizes"
                        layout="total,sizes,prev,pager,next,jumper" :total="pageResult.total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>

        <!-- 选择设备的对话框 -->
        <el-dialog v-model="deviceSelectDialogVisible" title="选择设备" width="800" @close="closeDeviceSelectDialog">
            <el-table :data="deviceLedger" style="width: 100%" @selection-change="handleDeviceSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="40" />
                <el-table-column prop="deviceNo" label="设备编码" align="center" />
                <el-table-column prop="deviceName" label="设备名称" align="center" />
                <el-table-column prop="brand" label="品牌" align="center" />
                <el-table-column prop="specificationModel" label="规格型号" align="center" />
                <el-table-column label="备注" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.remark.length > 10">{{ scope.row.remark.substring(0, 10) }}...</span>
                        <span v-else>{{ scope.row.remark }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeDeviceSelectDialog">取消</el-button>
                    <el-button type="primary" @click="confirmDeviceSelection">确认</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="dialogFormVisible" :title="title" width="800" @close="closeDialog">
            <el-form :model="form">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="维修单编号" :label-width="formLabelWidth">
                            <el-input v-model="form.repairNo" autocomplete="off" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="维修单名称" :label-width="formLabelWidth">
                            <el-input v-model="form.repairName" placeholder="请输入维修单名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="设备编号" :label-width="formLabelWidth">
                            <el-input v-model="form.deviceNo" style="max-width: 600px" placeholder="输入客户编码"
                                class="input-with-select">
                                <template #append>
                                    <el-button :icon="Search" @click="repairSelect" />
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设备名称" :label-width="formLabelWidth">
                            <el-input v-model="form.deviceName" autocomplete="off" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="品牌" :label-width="formLabelWidth">
                            <el-input v-model="form.brand" autocomplete="off" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="保修日期" :label-width="formLabelWidth">
                            <el-date-picker v-model="form.repairTime" type="date" placeholder="选择保修日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20" style="margin-top: 20px;">
                    <el-col :span="24">
                        <el-form-item label="备注" :label-width="formLabelWidth">
                            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注"
                                style="width: 100%;"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmAdd">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { deletetpmPlan, findwx, inserttpmPlan, updatestpmPlan } from '@/apis/zs/index';
import { onMounted, ref, reactive } from 'vue';
import { Search, Refresh, Delete, Plus, EditPen } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const dialogFormVisible = ref(false);
const deviceSelectDialogVisible = ref(false); // 控制选择设备弹窗的显示
const title = ref('');
let planNo = ref([]); // 选中行的id数组
const tableData = ref([]); // 表格数据
const pageResult = ref({}); // 分页数据
const deleteDisabled = ref(true); // 删除按钮禁用状态, 默认禁用
const open = ref(false); // 显示对话框
const deviceLedger = ref([]); // 设备台账数据
const form = reactive({
    repairNo: '',
    repairName: '',
    deviceNo: '',
    deviceName: '',
    brand: '',
    repairTime: '',
    remark: ''
});

// 搜索参数
const params = ref({
    currentPage: 1,
    pageSize: 2,
    repairNo: '',
    repairName: ''
});

// 分页大小
const pageSizes = [2, 5, 8, 10];

onMounted(async () => {
    pageResult.value = await findwx(params.value);
    tableData.value = pageResult.value.records;
});

// 打开设备选择对话框
const repairSelect = () => {
    deviceSelectDialogVisible.value = true;
    // 在这里可以添加获取设备数据的逻辑
};

// 关闭设备选择对话框
const closeDeviceSelectDialog = () => {
    deviceSelectDialogVisible.value = false;
};

// 确认设备选择
const confirmDeviceSelection = () => {
    // 在这里执行将选中设备信息填充到表单的逻辑
    closeDeviceSelectDialog();
};

// 处理设备选择变化（如果需要）
const handleDeviceSelectionChange = (val) => {
    // 处理选择的逻辑
};

// 点击新增
const openInsert = () => {
    dialogFormVisible.value = true;
    title.value = '新增设备维修单';
};

// 打开修改对话框
const openUpdate = (row) => {
    dialogFormVisible.value = true;
    title.value = '修改设备维修单';
    form.repairNo = row.repairNo;
    form.repairName = row.repairName;
    form.deviceNo = row.equipment.deviceNo;
    form.deviceName = row.equipment.deviceName;
    form.brand = row.equipment.brand;
    form.repairTime = row.equipment.repairTime;
    form.remark = row.remark;
};

// 确认新增或修改
const confirmAdd = async () => {
    if (title.value === '新增设备维修单') {
        await inserttpmPlan(form);
        ElMessage.success('新增成功');
    } else {
        await updatestpmPlan(form);
        ElMessage.success('修改成功');
    }
    dialogFormVisible.value = false;
    pageResult.value = await findwx(params.value);
    tableData.value = pageResult.value.records;
};

// 处理搜索
const handleSearch = async () => {
    pageResult.value = await findwx(params.value);
    tableData.value = pageResult.value.records;
};

// 处理重置
const handleReset = async () => {
    params.value = {
        currentPage: 1,
        pageSize: 2,
        repairNo: '',
        repairName: ''
    };
    pageResult.value = await findwx(params.value);
    tableData.value = pageResult.value.records;
};

// 处理分页大小变化
const handleSizeChange = async (size) => {
    params.value.pageSize = size;
    pageResult.value = await findwx(params.value);
    tableData.value = pageResult.value.records;
};

// 处理当前页码变化
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage;
    pageResult.value = await findwx(params.value);
    tableData.value = pageResult.value.records;
};

// 处理选中行变化
const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length;
    planNo.value = val.map(item => item.planNo); // 使用map方法过滤出选中行的id数组
};

// 处理删除选中行
const handleDelete = async () => {
    ElMessageBox.confirm(`是否确认删除访问编号为 ${planNo.value.join(',')} 的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deletetpmPlan(planNo.value);
        pageResult.value = await findwx(params.value);
        tableData.value = pageResult.value.records;
        planNo.value = []; // 重置选中行的id数组
        ElMessage({ type: 'success', message: '删除成功' });
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};

// 删除指定行
const deleteItem = async (row) => {
    ElMessageBox.confirm(`是否确认删除设备类型编码为 ${row.planNo} 的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deletetpmPlan([row.planNo]);
        tableData.value = tableData.value.filter(item => item.planNo !== row.planNo);
        ElMessage({ type: 'success', message: '删除成功' });
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};

// 清空所有记录
const clearAll = async () => {
    ElMessageBox.confirm(`是否确认清空所有登录日志数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deletetpmPlan(planNo.value);
        pageResult.value = await findwx(params.value);
        tableData.value = pageResult.value.records;
        planNo.value = []; // 重置选中行的id数组
        ElMessage({ type: 'success', message: '清空成功' });
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消清空' });
    });
};
</script>

<style scoped>
.dividing-line {
    text-align: center;
}

.button-right {
    text-align: right;
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}

.demo-pagination-block .el-pagination {
    justify-content: end;
    margin-top: 20px;
}
</style>
